package my2Cents;

import java.io.Serializable;
import java.util.Vector;

import net.phys2d.raw.Body;
import net.phys2d.raw.World;

public class UndoList extends Vector<Undo> implements Serializable {
	private static final long serialVersionUID = 1L;
	private World world;
	public static Object UNDO_TYPE_ALL = null;
	
	public UndoList(World world) {
		this.world = world;
	}

	public Undo undoLast() {
		Undo unDone = null;
		checkElements();
		if(size() > 0) {
			Undo u = (Undo) lastElement();
			unDone = u;
			u.performUndo();
			remove(u);
		}
		return unDone;
	}

	public void undoAll() {
		checkElements();
		if(size() > 0) {
			for(int i=0; i<size(); i++) {
				Undo u = (Undo) get(i);
				u.performUndo();
			}
			removeAllElements();
		}
	}
	
	public void undo(Object j, String type) {
		Undo u = getUndo(j, type);
		if(u != null) {
			u.performUndo();
			remove(u);
		}
	}
	
	public Undo getUndo(Object o, String type) {
		if(size() > 0) {
			for(int i=0; i<size(); i++) {
				Undo u = get(i);
				if(type != null) {
					if(u.getObject() == o && u.getUndoText().equals(type)) {
						return u;
					}
				} else {
					if(u.getObject() == o) {
						return u;
					}
				}
			}
		}
		return null;
	}
	
	public void undo(Object[] list) {
		for(int i=0; i<list.length; i++) {
			undo(list[i], null);
		}
	}
	
	public boolean add(Undo u) {
		//Undo u = new Undo(o, world);
		return super.add(u);
	}
	
	public boolean hasUndoObject(Undo o) {
		checkElements();
		return (getUndo(o,null) != null);
	}
	
	public void checkElements() {
		for(int i=0; i<size(); i++) {
			Undo u = (Undo) get(i);
			if(!u.isValid()) {	
				remove(u);
			}
		}
	}
}
